package com.doge.calcalbum.core

import android.Manifest
import android.app.AlertDialog
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.activity.result.contract.ActivityResultContracts
import androidx.annotation.RequiresApi
import androidx.core.content.PermissionChecker
import com.doge.calcalbum.utils.appContext
import java.lang.StringBuilder

@RequiresApi(Build.VERSION_CODES.M)
class RequestPermissionActivity : BaseActivity() {
    private val launcher by lazy {
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { _ ->
            val permissions = intent.getStringArrayExtra("permissions")!!
            when {
                permissions.none { PermissionChecker.PERMISSION_GRANTED != PermissionChecker.checkSelfPermission(
                    appContext, it) } -> {
                    PermissionUtil.notifyCallback(intent.getLongExtra("callbackId", -1), true)
                    supportFinishAfterTransition()
                }
                else -> requestPermissions(permissions, 0x0001)
            }
        }
    }

    override val portraitOrientation = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        overridePendingTransition(0, 0)
        launcher.toString()
        requestPermissions(intent.getStringArrayExtra("permissions")!!, 0x0001)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(0, 0)
    }

    override fun onBackPressed() = Unit


    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when {
            grantResults.none { PermissionChecker.PERMISSION_GRANTED != it } -> {
                PermissionUtil.notifyCallback(intent.getLongExtra("callbackId", -1), true)
                supportFinishAfterTransition()
            }
            permissions.any { !shouldShowRequestPermissionRationale(it) } -> showToSettingsDialog(permissions)
            else -> showHintDialog(permissions)
        }

    }


    private fun showHintDialog(permissions: Array<out String>) {
        AlertDialog.Builder(this).setTitle("权限不足")
                .setMessage(getDialogMessageContent(permissions))
                .setCancelable(false)
                .setPositiveButton("去授权") { _, _ ->
                    requestPermissions(permissions, 0x0001)
                }.setNegativeButton("取消") { _, _ ->
                    PermissionUtil.notifyCallback(intent.getLongExtra("callbackId", -1), false)
                    supportFinishAfterTransition()
                }.create().show()
    }


    private fun showToSettingsDialog(permissions: Array<out String>) {
        AlertDialog.Builder(this).setTitle("权限不足")
                .setMessage(getDialogMessageContent(permissions))
                .setCancelable(false)
                .setPositiveButton("去设置") { _, _ ->
                    launcher.launch(Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).setData(Uri.fromParts("package", packageName, null)))
                }.setNegativeButton("取消") { _, _ ->
                    PermissionUtil.notifyCallback(intent.getLongExtra("callbackId", -1), false)
                    supportFinishAfterTransition()
                }.create().show()
    }

    private fun getDialogMessageContent(permissions: Array<out String>): String {
        val sb = StringBuilder()
        permissions.forEach {
            sb.append(when (it) {
                Manifest.permission.CAMERA -> if (sb.contains("相机、")) "" else "相机、"
                Manifest.permission.MANAGE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE -> if (sb.contains("存储、")) "" else "存储、"
                Manifest.permission.RECORD_AUDIO -> if (sb.contains("录音、")) "" else "录音、"
                Manifest.permission.ACCESS_BACKGROUND_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION -> if (sb.contains("位置信息、")) "" else "位置信息、"
                Manifest.permission.READ_PHONE_STATE, Manifest.permission.READ_PRECISE_PHONE_STATE -> if (sb.contains("设备信息、")) "" else "设备信息、"
                else -> ""
            })
        }
        val permissionList = if (sb.isEmpty()) "部分权限" else sb.substring(0, sb.length - 1)
        return "为了保证此项服务的正常使用，应用需要申请${permissionList}等权限；如果你选择了拒绝，那么此项服务将不可用，你仍可使用应用的提供的其它服务。"
    }

}